import React, { useState, useEffect, forwardRef, useImperativeHandle } from "react"
import {
    Radio,
    InputNumber,
    Button,
    Icon,
    message,
    Space,
    Input,
    Form
} from "@bytedance/mona-ui"
import { useAppDispatch } from "~store"
import {
    setLadderPriceList,
    setFixedPriceList,
    setPriceGroupAction
} from "~store/controller/jinritemaiCopyGoods"
const PriceAndInventory = (props: any, ref) => {
    const { goodsDetellData, copyGoodConfig } = props
    if (!goodsDetellData) return null
    // const displaySpecList = goodsDetellData.specs
    const { copynum } = copyGoodConfig
    // const displaySpecList = goodsDetellData.display_spec.displaySpecList
    // const { spec_prices } = goodsDetellData
    const dispatch = useAppDispatch()
    const [priceGroup, setPriceGroup] = useState<number>(1)
    //⬇️
    function addFixedPrice() {
        return {
            add_type: 3,
            price: '',
        }
    }
    function getFixedPl() {
        let ader: any = []
        for (let i = 0; i < copynum; i++) {
            ader.push(addFixedPrice())
        }
        return ader
    }
    const [fixedPrice, setFixedPrice] = useState<any[]>(getFixedPl())
    //⬇️
    function addLadderPrice() {
        return {
            add_type: 1,
            price: '',
        }
    }
    function addLadderLs() {
        let ader: any = []
        for (let i = 0; i < copynum; i++) {
            ader.push(addLadderPrice())
        }
        return ader
    }
    const [ladderPrice, setLadderPrice] = useState<any[]>(addLadderLs())
    const [addRefous, setAddRefous] = useState<any>({
        start: -0.1,
        end: 0.1
    })
    const [addConter, astAllConter] = useState<any>({
        add_type: 1,
        price: '',
    })
    const [addPrigterDater, setAddPrigterDater] = useState<any>({
        start: '1',
        end: '',
        add_type: 1,
    })

    function fullClose(n, m) {
        var result = Math.random() * (m + 1 - n) + n;
        while (result > m) {
            result = Math.random() * (m + 1 - n) + n;
        }
        return (result * 1).toFixed(2);
    }
    // useEffect(() => {
    //     dispatch(setLadderPriceList(JSON.parse(JSON.stringify(ladderPrice))))
    //     dispatch(setFixedPriceList(JSON.parse(JSON.stringify(fixedPrice))))
    //     dispatch(setPriceGroupAction(priceGroup))
    // }, [ladderPrice, fixedPrice, priceGroup])
    useImperativeHandle(ref, () => ({
        ladderPrice,
        fixedPrice,
        priceGroup
    }));
    useEffect(() => {
        if (fixedPrice.length === copynum) {
            return
        }
        const addConter = copynum - fixedPrice.length
        if (addConter > 0) {
            for (let i = 0; i < addConter; i++) {
                fixedPrice.push(addFixedPrice())
            }
        } else {
            fixedPrice.splice(addConter, Math.abs(addConter))
        }
        setFixedPrice([...fixedPrice])

        if (ladderPrice.length === copynum) {
            return
        }
        const addConterouer = copynum - ladderPrice.length
        if (addConterouer > 0) {
            for (let i = 0; i < addConterouer; i++) {
                ladderPrice.push(addLadderPrice())
            }
        } else {
            ladderPrice.splice(addConterouer, Math.abs(addConterouer))
        }
        setLadderPrice([...ladderPrice])


    }, [copynum])

    return (<div style={{
        marginLeft: '25px',
    }}>
        <Space direction="vertical">
            <Radio.Group
                value={priceGroup}
                onChange={(e) => {
                    setPriceGroup(e.target.value)
                }}>

                <Radio value={1}>
                    阶梯价格
                </Radio>
                <Radio value={2}>
                    一口价
                </Radio>
                {/* <Radio value={3}>
                    浮动价格
                </Radio> */}
            </Radio.Group>

            {priceGroup === 1 && (<>
                {false && <Button
                    size="mini"
                    disabled={ladderPrice.length >= copyGoodConfig.copynum}
                    type="primary"
                    onClick={(e) => {
                        if (ladderPrice.length >= copyGoodConfig.copynum) return
                        ladderPrice.push(addLadderPrice())
                        setLadderPrice([...ladderPrice])
                    }}>
                    新增阶梯价格
                </Button>}

                <Space>
                    <Space size={4}>
                        <span>增加范围(负数为减, 正数为增)</span>
                        <Input.Group compact >
                            <Input wrapperStyle={{ width: 80, textAlign: 'center' }} placeholder="开始" value={addRefous.start} prefix="￥" onChange={(e: any) => {
                                addRefous.start = e.target.value
                                setAddRefous({ ...addRefous })
                            }} />
                            <Input
                                className="site-input-split"
                                wrapperStyle={{
                                    width: 30,
                                    borderLeft: 0,
                                    borderRight: 0,
                                    pointerEvents: 'none',
                                }}
                                placeholder="~"
                                disabled

                            />
                            <Input
                                className="site-input-right"
                                wrapperStyle={{
                                    width: 80,
                                    textAlign: 'center',
                                }}
                                value={addRefous.end}
                                prefix="￥"

                                placeholder="结束"
                                onChange={(e: any) => {
                                    // console.log('eee', e)
                                    // console.log('eee', e.target.value)
                                    addRefous.end = e.target.value
                                    setAddRefous({ ...addRefous })
                                }}
                            />
                        </Input.Group>
                    </Space>

                    <Button type="primary" size="mini" onClick={() => {
                        // console.log('123456', addRefous)
                        // console.log(fullClose(addRefous.start, addRefous.end))
                        // const addPritList:any = []
                        if (addRefous.start * 1 > addRefous.end * 1) {
                            message.warn('请输入正确的价格区间')
                            return
                            // item.add_type = 2
                            // item.price = Math.abs(fullClose(addRefous.start*1, addRefous.end*1))
                        }
                        if (addRefous.start === addRefous.end) {
                            message.warn('请输入正确的价格区间')
                            return
                        }
                        ladderPrice.forEach((item: any, index: number) => {
                            // addPritList.push(fullClose(addRefous.start*1, addRefous.end*1))

                            const addPrice: any = fullClose(addRefous.start * 1, addRefous.end * 1)
                            if (addPrice > 0) {
                                item.add_type = 1
                                item.price = Math.abs(addPrice * 1)
                            }
                            if (addPrice < 0) {
                                item.add_type = 2
                                item.price = Math.abs(addPrice)
                            }
                        })
                        setLadderPrice([...ladderPrice])
                        // console.log('addPritList', addPritList)
                    }}>随机填充</Button>
                </Space>
                <Space>
                    批量填写价格区间
                    <Input
                        prefix={
                            <Radio.Group
                                value={addConter.add_type}
                                optionType="button"
                                size="small"
                                buttonStyle="solid"
                                onChange={e => {
                                    addConter.add_type = e.target.value
                                    astAllConter({ ...addConter })
                                }}
                            >
                                <Radio.Button value={1}>增</Radio.Button>
                                <Radio.Button value={2}>减</Radio.Button>
                            </Radio.Group>}
                        size="small"
                        placeholder="请输入阶梯价格"
                        value={addConter.price}
                        // step={0.01}
                        min={0.01}
                        onChange={(e: any) => {
                            var regex = /^\d*\.?\d*$/;
                            if (regex.test(e.target.value)) {
                                addConter.price = e.target.value
                                astAllConter({ ...addConter })
                            }
                        }} />
                    <Button type="primary" size="mini" onClick={() => {
                        if (!addConter.price) return message.warning('请输入数字')
                        let infos = addConter.price
                        ladderPrice.forEach((item: any) => {
                            item.price = infos
                            item.add_type = addConter.add_type
                            infos = ((infos * 1) + (addConter.price * 1)).toFixed(2)
                        })
                        setLadderPrice([...ladderPrice])
                    }}>批量填充</Button>
                </Space>
                <Space>
                    批量填写阶梯价格区间
                    <Radio.Group
                        value={addPrigterDater.add_type}
                        optionType="button"
                        size="small"
                        buttonStyle="solid"
                        onChange={e => {
                            addPrigterDater.add_type = e.target.value
                            setAddPrigterDater({ ...addPrigterDater })
                        }}
                    >
                        <Radio.Button value={1}>增</Radio.Button>
                        <Radio.Button value={2}>减</Radio.Button>
                    </Radio.Group>
                    <InputNumber.Group prefix="￥" startProps={{
                        // size: 'small',
                        size: "middle",
                        style: {
                            width: 100,
                        },
                        step: 0.01,
                        min: 0.01,
                        // value: addPrigterDater.start,
                    }} endProps={{
                        size: "middle",
                        style: {
                            width: 100,
                        },
                        step: 0.01,
                        min: 0.01,
                    }} onChange={e => {
                        // console.log('e', e)
                        e[0] && (addPrigterDater.start = e[0])
                        e[1] && (addPrigterDater.end = e[1])
                        // addPrigterDater.end = e.target.value
                        setAddPrigterDater({ ...addPrigterDater })
                    }} />
                    <Button type="primary" size="mini" onClick={() => {
                        if (!addPrigterDater.start || !addPrigterDater.end) return message.warning('请输入数字')
                        if (addPrigterDater.start > addPrigterDater.end) return message.warning('开始需要小于结束')
                        if (addPrigterDater.start == addPrigterDater.end) {
                            ladderPrice.forEach((item: any) => {
                                item.price = addPrigterDater.start
                                item.add_type = addPrigterDater.add_type
                                // infos = ((infos * 1) + (addConter.price * 1)).toFixed(2)
                            })
                        }
                        else {
                            const contentAler = addPrigterDater.end - addPrigterDater.start
                            // console.log('contentAler', contentAler, contentAler / copynum)
                            const stip: any = (contentAler / copynum).toFixed(2)
                            let addInter = 0
                            let stopaddAlin: any = []
                            ladderPrice.forEach((item: any, index: number) => {
                                stopaddAlin.push(addInter)

                                addInter = addInter + (stip * 1)
                            })
                            ladderPrice.forEach((item: any, index: number) => {
                                item.price = (addPrigterDater.start + stopaddAlin[index]).toFixed(2)
                                item.add_type = addPrigterDater.add_type
                            })
                            console.log('addInter', addPrigterDater.start, stopaddAlin, stip)


                        }

                        setLadderPrice([...ladderPrice])
                    }}>批量填充</Button>
                </Space>
                {/* <Form layout="inline">
                    <Form.Item label="增加范围（负<->数为减, 正<+>数为增）">
                        <Input.Group compact size="small">
                            <Input wrapperStyle={{ width: 80, textAlign: 'center' }} placeholder="开始" value={addRefous.start} prefix="￥" size="small" onChange={(e: any) => {
                                addRefous.start = e.target.value
                                setAddRefous({ ...addRefous })
                            }} />
                            <Input
                                className="site-input-split"
                                wrapperStyle={{
                                    width: 30,
                                    borderLeft: 0,
                                    borderRight: 0,
                                    pointerEvents: 'none',
                                }}
                                placeholder="~"
                                disabled
                                size="small"
                            />
                            <Input
                                className="site-input-right"
                                wrapperStyle={{
                                    width: 80,
                                    textAlign: 'center',
                                }}
                                value={addRefous.end}
                                prefix="￥"
                                size="small"
                                placeholder="结束"
                                onChange={(e: any) => {
                                    // console.log('eee', e)
                                    // console.log('eee', e.target.value)
                                    addRefous.end = e.target.value
                                    setAddRefous({ ...addRefous })
                                }}
                            />
                        </Input.Group>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" size="mini" onClick={() => {
                            console.log('123456', addRefous)
                        }}>随机填充</Button>
                    </Form.Item>
                </Form> */}

                {ladderPrice.map((item, index) => {
                    return (<Space key={index}>
                        <div className="cjenr">价格 {index + 1}</div>
                        <Input
                            prefix={
                                <Radio.Group
                                    value={item.add_type}
                                    optionType="button"
                                    size="small"
                                    buttonStyle="solid"
                                    onChange={e => {
                                        ladderPrice[index].add_type = e.target.value
                                        setLadderPrice([...ladderPrice])
                                    }}
                                >
                                    <Radio.Button value={1}>增</Radio.Button>
                                    <Radio.Button value={2}>减</Radio.Button>
                                </Radio.Group>}
                            size="small"
                            placeholder="请输入阶梯价格"
                            value={item.price}
                            // step={0.01}
                            min={0.01}
                            onChange={(e: any) => {
                                // console.log('ABC', e.target.value)
                                // console.log('ABC22', e.target)


                                var regex = /^\d*\.?\d*$/;
                                if (regex.test(e.target.value)) {
                                    ladderPrice[index].price = e.target.value
                                    setLadderPrice([...ladderPrice])
                                }
                            }} />
                        {false && <Icon
                            type="DeleteIcon"
                            style={{ color: 'red', fontSize: '20px' }}
                            onClick={() => {
                                if (ladderPrice.length === 1) {
                                    message.warning('至少保留一个配置')
                                    return
                                }
                                ladderPrice.splice(index, 1)
                                setLadderPrice([...ladderPrice])
                            }}></Icon>}
                    </Space>)
                })}
            </>)}
            {priceGroup === 2 && (<>
                {false && <Button
                    size="mini"
                    disabled={fixedPrice.length >= copyGoodConfig.copynum}
                    type="primary"
                    onClick={(e) => {
                        if (fixedPrice.length >= copyGoodConfig.copynum) return
                        fixedPrice.push(addFixedPrice())
                        setFixedPrice([...fixedPrice])
                    }}>新增一口价格</Button>}
                {fixedPrice.map((item, index) => {
                    return (<Space key={index}>
                        <div className="cjenr">价格 {index + 1}</div>
                        <InputNumber
                            size="small"
                            placeholder="请输入固定价格"
                            value={item.price}
                            step={0.01}
                            min={0.01}
                            onChange={(e) => {
                                fixedPrice[index].price = e
                                setFixedPrice([...fixedPrice])
                            }} />
                        {false && <Icon
                            type="DeleteIcon"
                            style={{ color: 'red', fontSize: '20px' }}
                            onClick={() => {
                                if (fixedPrice.length === 1) {
                                    message.warning('至少保留一个配置')
                                    return
                                }
                                fixedPrice.splice(index, 1)
                                setFixedPrice([...fixedPrice])
                            }}></Icon>}
                    </Space>)
                })}

            </>)}
        </Space>
    </ div>)
}


export default forwardRef(PriceAndInventory)